package java学习.第16章_网络编程;

import org.junit.Test;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

/**
 * ClassName: F_UDP
 * Package: java学习.第16章_网络编程
 * Description:
 *
 * @Author 张蛟龙
 * @Create 2023/4/15 14:43
 * @Version 1.0
 */
public class F_UDP {
    @Test
    public void 服务端(){
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(65533);

            byte[] bytes = new byte[100];
            //数据包
            DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length);

            while (true){

                socket.receive(packet);//接受数据
                String s = new String(packet.getData(), 0, packet.getLength());
                if(s.equals("结束")){
                    break;
                }
                //输出s
                System.out.println(s);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {

            socket.close();
        }
    }
    @Test
    public static void 客户端(){
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket();

            InetAddress inet = InetAddress.getByName("127.0.0.1");
            Scanner s = new Scanner(System.in);
            while (true){
                String str = s.nextLine();
                byte[] bytes = str.getBytes();
                DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length,inet,65533);
                socket.send(packet);//发送数据
                if(str.equals("结束")){
                    break;
                }
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            socket.close();
        }

    }

    public static void main(String[] args) {
        客户端();
    }
}
